package org.shiftone.cdep.store;

import org.apache.log4j.Logger;
import org.shiftone.cdep.util.JDBCUtil;
import org.shiftone.cdep.store.AbstractStoreManager;

import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.Statement;

public class HsqlStoreManager extends AbstractStoreManager
{
    public static final Logger LOG = Logger.getLogger(HsqlStoreManager.class);

    public HsqlStoreManager()
    {
    }

    protected String prepareInsertQuery(String methodName, String query, boolean generateKey)
    {
//        return query + " call IDENTITY()";
        return query;
    }

    protected String prepareUpdateQuery(String methodName, String query)
    {
        return query;
    }

    protected String prepareSelectQuery(String methodName, String query)
    {
        return query;
    }

    protected String prepareDeleteQuery(String methodName, String query)
    {
        return query;
    }

    protected int executeInsert(PreparedStatement stmt, boolean generateKey) throws SQLException
    {
        if (generateKey)
        {
            if (stmt.executeUpdate() != 1)
            {
                throw new SQLException("Failed to insert row");
            }

            Connection conn = getConnection();
            PreparedStatement ps = null;
            ResultSet rs = null;

            try
            {
                ps = conn.prepareStatement("call IDENTITY();");
                rs = ps.executeQuery();
                if (rs.next())
                {
                    return rs.getInt(1);
                }
            }
            finally
            {
                JDBCUtil.close(rs);
                JDBCUtil.close(ps);
                closeConnection();
            }
        }
        else
        {
            return stmt.executeUpdate();
        }

        return 0;
    }

    protected void executeDelete(PreparedStatement stmt) throws SQLException
    {
        if (stmt.executeUpdate() < 1)
        {
            throw new SQLException("Failed to update any rows");
        }
    }

    protected ResultSet executeSelect(PreparedStatement stmt) throws SQLException
    {
        return stmt.executeQuery();
    }

    protected void executeUpdate(PreparedStatement stmt) throws SQLException
    {
        if (stmt.executeUpdate() < 1)
        {
            throw new SQLException("Failed to update any rows");
        }
    }

    public void shutdown()
    {
        Connection conn = getConnection();
        Statement stmt = null;

        try
        {
            stmt = conn.createStatement();

            stmt.execute("SHUTDOWN");

        }
        catch (SQLException sex)
        {
            LOG.error(sex);
        }
        finally
        {
            JDBCUtil.close(stmt);
            closeConnection();
        }
    }
}
